package com.xhdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xhdp.dto.Result;
import com.xhdp.entity.ShopType;
import com.xhdp.mapper.ShopTypeMapper;
import com.xhdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xhdp.utils.RedisConstants.CACHE_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaohe
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     * @return
     */
    public Result queryTypeList() {
        //查询redis缓存
        String typeJson = stringRedisTemplate.opsForValue().get(CACHE_TYPE_KEY);
        //判断缓存是否存在
        if (StrUtil.isNotBlank(typeJson)) {
            //存在缓存，返回数据
            List<ShopType> shopTypeList = JSONUtil.toList(typeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //不存在缓存，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //数据库不存在数据
        if (shopTypeList.isEmpty()) {
            return Result.fail("数据不存在！");
        }
        //放入redis缓存
        stringRedisTemplate.opsForValue().set(CACHE_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));
        //返回数据
        return Result.ok(shopTypeList);
    }
}
